package com.v2future.sjt.collegecheckingattendance.fruit;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;

import com.v2future.sjt.collegecheckingattendance.MainActivity;
import com.v2future.sjt.collegecheckingattendance.R;
import com.v2future.sjt.collegecheckingattendance.event.adapter.ReleaseEventImgGridAdapter;
import com.v2future.sjt.collegecheckingattendance.event.bean.ReleaseEventImageBean;
import com.v2future.sjt.collegecheckingattendance.fruit.bean.ConditionTypeBean;
import com.v2future.sjt.collegecheckingattendance.fruit.bean.FruitAddRequestBean;
import com.v2future.sjt.collegecheckingattendance.utils.BaseResponseBean;
import com.v2future.sjt.collegecheckingattendance.utils.Constants;
import com.v2future.sjt.collegecheckingattendance.utils.IntentKey;
import com.v2future.sjt.collegecheckingattendance.utils.netutils.BaseRequestParams;
import com.v2future.sjt.collegecheckingattendance.utils.netutils.NetTaskListener;
import com.v2future.sjt.collegecheckingattendance.utils.netutils.NetUtils;
import com.v2future.sjt.collegecheckingattendance.widget.DateTimePickDialogUtil;

import java.util.ArrayList;
import java.util.List;

import me.nereo.multi_image_selector.MultiImageSelectorActivity;

/**
 * 发布成长
 * @author shijianting
 * @time 2016/4/21 19:30
 */
public class AddFruitActivity extends MainActivity implements View.OnClickListener{

    private EditText contentEt;

    private EditText titleEt;

    private EditText addrEt;

    private Button timeBtn;

    private Button submitBtn;

    GridView gvReleaseImages;

    private ConditionTypeBean conditionTypeBean;

    /**
     * 适配器装载图片的列表
     */
    List<ReleaseEventImageBean> imageDataList;

    /**
     * 图片展示适配器
     */
    ReleaseEventImgGridAdapter adapter;

    int REQUEST_IMAGE = 1001;

    /**
     * init first
     */
    @Override
    public void init() {
        conditionTypeBean = (ConditionTypeBean) getIntent().getSerializableExtra(IntentKey.FRUIT_TYPE);
        imageDataList = new ArrayList<>();
        ReleaseEventImageBean bean = new ReleaseEventImageBean();
        imageDataList.add(bean);
    }

    /**
     * init view
     */
    @Override
    public void initView() {
        setContentView(R.layout.activity_add_fruit);
        setTitleText(conditionTypeBean.getConditonTypeName());
        initTitleBack(null);
        contentEt = (EditText) findViewById(R.id.et_content);
        titleEt = (EditText) findViewById(R.id.et_title);
        addrEt = (EditText) findViewById(R.id.et_addr);
        timeBtn = (Button) findViewById(R.id.btn_time);
        timeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DateTimePickDialogUtil dateTimePicKDialog = new DateTimePickDialogUtil(
                        AddFruitActivity.this, null);
                dateTimePicKDialog.dateTimePicKDialog(timeBtn);
            }
        });
        submitBtn = (Button) findViewById(R.id.btn_submit);
        submitBtn.setOnClickListener(this);
        gvReleaseImages = (GridView) findViewById(R.id.gv_release_images);
        gvReleaseImages.setOnItemClickListener(imageClickListener);
    }

    /**
     * init after
     */
    @Override
    public void initAfter() {
        adapter = new ReleaseEventImgGridAdapter(this, imageDataList);
        gvReleaseImages.setAdapter(adapter);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == REQUEST_IMAGE){
            if(resultCode == RESULT_OK){
                // Get the result list of select image paths
                ArrayList<String> path = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                if (path.size() > 0 ) {
                    imageUrls = path;//保存已选的图片路径
                    refreshImages(path);
                    showLoadingDialog();
                    new Thread(){
                        @Override
                        public void run() {
                            super.run();
                            compressImages();
                            cancelLoadingDialog();
                        }
                    }.start();
                }
            }
        }
    }

    /**
     * 刷新图片
     */
    private void refreshImages(ArrayList<String> path){
        imageDataList.clear();
        ReleaseEventImageBean bean = null;
        for (int i=0;i<path.size();i++) {
            bean = new ReleaseEventImageBean();
            bean.setImageUrl(path.get(i).toString());
            imageDataList.add(bean);
        }
        bean = new ReleaseEventImageBean();
        imageDataList.add(bean);
        adapter.notifyDataSetChanged();
    }

    /**
     * 添加成长
     * @param bean 参数
     */
    private void doAddUserFruit(FruitAddRequestBean bean){
        BaseRequestParams params = new BaseRequestParams(this, formatUrlDo(Constants.PUBLISH_EVENT));
        params.setMultipart(true);
        params.addQueryStringParameter("type", "3");//3表示发布成长
        params.addQueryStringParameter("conditionDesc", bean.getContent());
        params.addQueryStringParameter("condtionTypeId", bean.getConditionType());
        params.addQueryStringParameter("conditionTitle", bean.getConditionTitle());
        params.addQueryStringParameter("conditionArea", bean.getConditionArea());
        params.addQueryStringParameter("conditionDesc", bean.getConditionDesc());
        params.addQueryStringParameter("researchSubjectId", bean.getResearchSubjectId());
        params.addQueryStringParameter("researchRemark", bean.getResearchRemark());
        params.addQueryStringParameter("researchDesc", bean.getResearchDesc());
        params.addQueryStringParameter("conditionUnit", bean.getConditionUnit());
        params.addQueryStringParameter("conditionLevel", bean.getConditionLevel());
//        params.addQueryStringParameter("conditionDate", bean.getConditionDate());
        if (null != imageUrls && imageUrls.size() > 0) {
            for (int i=0;i<imageUrls.size();i++) {
                params.addQueryStringParameter("imageName"+i, urlEncode(imageUrls.get(i).toString()));
                params.addBodyParameter("imageBody"+i, imageFiles.get(i), null);
            }
        }
        NetUtils.doPostRequestWithFiles(this, params, new NetTaskListener<BaseResponseBean>() {

            /**
             * 数据获取完成
             *
             * @param result
             */
            @Override
            public void onSuccess(BaseResponseBean result) {
                showOneBtnDialog(getString(R.string.notice), "提交成长完成", getString(R.string.iknow), new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish();
                    }
                });
            }

            /**
             * 位置网络错误
             */
            @Override
            public void onError() {

            }

            /**
             * 非正常状态的数据
             *
             * @param result
             */
            @Override
            public void onInterError(BaseResponseBean result) {
                tip(result.getFailReason());
            }

            /**
             * 网络错误
             *
             * @param responseCode
             * @param responseMsg
             * @param errorResult
             */
            @Override
            public void onNetError(int responseCode, String responseMsg, String errorResult) {
                tip(responseMsg);
            }

            /**
             * 请求取消
             */
            @Override
            public void onCancelled() {

            }

            /**
             * 网络请求流程结束
             */
            @Override
            public void onFinished() {
                cancelLoadingDialog();
            }

            /**
             * 缓存获取完成
             *
             * @param result
             */
            @Override
            public void onSuccessCache(BaseResponseBean result) {

            }
        });
    }

    /**
     * Called when a view has been clicked.
     *
     * @param v The view that was clicked.
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_submit:
                if (TextUtils.isEmpty(titleEt.getText().toString())) {
                    tip("请输入标题");
                }
                if (TextUtils.isEmpty(contentEt.getText().toString())) {
                    tip("请输入内容");
                    break;
                }
                if (TextUtils.isEmpty(timeBtn.getText().toString())) {
                    tip("请输入时间");
                }
                if (TextUtils.isEmpty(addrEt.getText().toString())) {
                    tip("请输入时间");
                }
                FruitAddRequestBean bean = new FruitAddRequestBean();
                bean.setConditionTitle(titleEt.getText().toString());
                bean.setConditionType(conditionTypeBean.getConditonTypeId());
                bean.setContent(contentEt.getText().toString());
                bean.setConditionArea(addrEt.getText().toString());
                bean.setConditionDate(timeBtn.getText().toString());
                showLoadingDialog();
                doAddUserFruit(bean);
                break;
            default:
                break;
        }
    }

    AdapterView.OnItemClickListener imageClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//            if (dataList.get(position).getImageUrl() == null) {
            Intent intent = new Intent(AddFruitActivity.this, MultiImageSelectorActivity.class);
            // whether show camera
            intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, false);
            // max select image amount
            intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 4);
            // select mode (MultiImageSelectorActivity.MODE_SINGLE OR MultiImageSelectorActivity.MODE_MULTI)
            intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);
            // default select images (support array list)
            intent.putStringArrayListExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, imageUrls);
            startActivityForResult(intent, REQUEST_IMAGE);
//            }
        }
    };
}
